package com.zzzy.cont.service.mycon;

import com.zzzy.common.exception.BusinessException;
import com.zzzy.common.util.AssertUtil;
import com.zzzy.common.util.FileUtil;
import com.zzzy.cont.common.enums.ConStatusEnum;
import com.zzzy.cont.dao.entity.Contract;
import com.zzzy.framework.common.enums.sys.UserStatusEnum;
import com.zzzy.framework.common.util.SecurityUtils;
import com.zzzy.sys.dto.UserInfoDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;

@Service
public class MyConSignService extends MyConService {

    @Transactional
    public void applySign(Long id, Long userId) {
        Contract contract = getConByIdForUpdate(id);
        AssertUtil.isEquals(ConStatusEnum.SIGN.getValue(), contract.getStatus(), "合同状态错误，无法申请签订");
        Long loginUserId = SecurityUtils.getLoginUser().getId();
        AssertUtil.isNotEquals(userId, loginUserId, "选择的用户不能 为当前用户");
        AssertUtil.isTrue(userService.hasPermission(userId, "con:process:sign"), "选择的用户无签订权限，如有疑问，请联系管理员");
        UserInfoDto userInfoDto = userService.getUserInfoById(userId);
        AssertUtil.isEquals(UserStatusEnum.ENABLE.getValue(), userInfoDto.getStatus(), "选择的用户状态错误，无法申请签订，如有疑问，请联系管理员");
        contract.setUpdateTime(LocalDateTime.now());
        contract.setOperatorId(userId);
        contract.setOperatorName(userInfoDto.getNickName());
        baseMapper.updateById(contract);

        //添加合同动态
        conActivityNoteService.addSysNote(id, "申请签订至 " + userInfoDto.getNickName());

        String message = contract.getTradeCompany() +" - "+ contract.getName() + " 待签订";
        conNotifyMessageService.addNotifyMessage(id, userId, message);
    }

    @Transactional
    public void signComplete(Long id) {
        Contract contract = getConByIdForUpdate(id);
        AssertUtil.isEquals(ConStatusEnum.SIGN.getValue(), contract.getStatus(), "合同状态错误，无法进入履行阶段");
        contract.setStatus(ConStatusEnum.FULFILL.getValue());
        contract.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(contract);

        conFileHistoryService.addSignedHistory(id);
        //添加合同动态
        conActivityNoteService.addSysNote(id, "签订完毕，合同进入履行阶段");
    }
    @Transactional
    public void reAudit(Long id) {
        Contract contract = getConByIdForUpdate(id);
        AssertUtil.isEquals(ConStatusEnum.SIGN.getValue(), contract.getStatus(), "合同状态错误，无法重新审核");
        contract.setStatus(ConStatusEnum.AUDIT.getValue());
        contract.setUpdateTime(LocalDateTime.now());
        baseMapper.updateById(contract);
        conFileService.clearPdfIfHasWord(id);
        //添加合同动态
        conActivityNoteService.addSysNote(id, "合同重新审核");
    }

    /**
     * 上传对方盖章合同
     */
    @Transactional
    public void uploadSignFile(Long id, MultipartFile conFile) {
        byte[] byteFileBlob;
        try {
            byteFileBlob = conFile.getBytes();
        } catch (IOException e) {
            throw new BusinessException("文件读取错误");
        }
        //检测上传的文件类型是否合格有效
        String filename = conFile.getOriginalFilename();
        String extendType = filename.substring(filename.lastIndexOf(".") +1);
        if (!FileUtil.PDF.equalsIgnoreCase(extendType)){
            throw new BusinessException("上传文件类型不符，请上传扩展名为 pdf的有效合同文件。");
        }
        String fileType = FileUtil.getFileType(byteFileBlob);
        if (!StringUtils.equalsIgnoreCase(fileType, extendType)) {
            throw new BusinessException("上传文件类型不符，您可能手动修改过文件扩展名。请上传扩展名为 pdf的有效合同文件。");
        }

        updatePdf(id, byteFileBlob);
        //添加合同动态
        conActivityNoteService.addSysNote(id, "上传对方盖章合同");
    }
}
